package com.r2dbc.config;

import io.r2dbc.pool.ConnectionPool;
import io.r2dbc.pool.ConnectionPoolConfiguration;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.r2dbc.config.AbstractR2dbcConfiguration;
import java.time.Duration;
import static io.r2dbc.pool.PoolingConnectionFactoryProvider.MAX_SIZE;
import static io.r2dbc.spi.ConnectionFactoryOptions.*;

/**
 * @author r2dbc 数据库连接池
 */
@Configuration
public class DatabaseConfig extends AbstractR2dbcConfiguration {
    @Override
    @Bean
    public ConnectionFactory connectionFactory() {
        ConnectionFactory factory = ConnectionFactories.get(builder()
                .option(DRIVER, "pool")
                .option(PROTOCOL, "mysql")
                .option(HOST, "127.0.0.1")
                .option(PORT, 3306)
                .option(USER, "root")
                .option(PASSWORD, "root")
                .option(DATABASE, "test")
                .option(MAX_SIZE, 30)
                .build());

        ConnectionPoolConfiguration config = ConnectionPoolConfiguration.builder(factory)
                .maxIdleTime(Duration.ofMinutes(30))
                .initialSize(5)
                .maxSize(30)
                .maxCreateConnectionTime(Duration.ofSeconds(1))
                .build();

        return new ConnectionPool(config);
    }
}
